package com.sports.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sports.entity.Athletes;
import com.sports.entity.User;
import com.sports.mapper.AthletesMapper;
import com.sports.service.AdminService;
import com.sports.service.AthletesService;
import com.sports.service.JudgeService;
import com.sports.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private AthletesService athletesService;
    @Autowired
    private JudgeService judgeService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private AthletesMapper athletesMapper;
    @Override
    public boolean login(Integer id, String password, Integer role, HttpSession session) {
        
        User user = null;
        if(role==0){  //管理员
            user=adminService.getById(id);
        }else if(role==1){  //裁判
            user=judgeService.getById(id);
        }else if(role==2){  //运动员
            user=athletesService.getById(id);
        }

        if(user==null || !user.getPassword().equals(password)){
            //登录失败
            return false;
        }else{

            session.setAttribute("user",user);
            session.setAttribute("role",role);
            return true;
        }

    }

    @Override
    public Athletes register(Athletes athletes) {

        Athletes ath = athletesService.getById(athletes.getAthletesId());
        if(ath==null){
            athletesService.save(athletes);
            //注册成功 , 返回运动员信息
            QueryWrapper<Athletes> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("athletes_id").last("LIMIT 1");
            return athletesMapper.selectOne(queryWrapper);
        }else{
            return null;
        }
    }
}
